<?php
/**
 * Copyright 2013 Marek Kaszewski
 *
 * This file is part of the JHUB1 Online Community Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Jhub1_Common\Model\Key;

use Jhub1_Common\Model\Key\Generator;
use Jhub1_Common\Entity\BO\AbstractBO;

class UniqueKey
{
    private static $OBJECT_IDS = array( 'Jhub1_Common\Entity\BO\AgentsBO'         => 'A',
                                        'Jhub1_Common\Entity\BO\EndpointTypesBO'  => 'T',
                                        'Jhub1_Common\Entity\BO\EndpointValuesBO' => 'V',
                                        'Jhub1_Common\Entity\BO\UsersBO'          => 'U',
                                         );
    private $bo;
    private $currentObjectId;

    public function __construct(AbstractBO $bo)
    {
        $this->currentObjectId = $this->determineObjectID($bo);
        $this->bo = $bo;

    }

    private function determineObjectID($instance)
    {
        return UniqueKey::$OBJECT_IDS[get_class($instance)];
    }

    public static function getObjectTypeByUUID($uuid)
    {
        $class = Generator::getUUIDClass($uuid);
        $POClass = '';
        foreach(UniqueKey::$OBJECT_IDS as $key => $value)
        {
            if($class == $value){
                $POClass = $key;
            }
        }
        return $POClass;
    }

    public function getUUID() {
        if($this->currentObjectId == null) {
            //throw exception
        }
        $uuid = '';
        while($uuid == '' || !$this->bo->isPKUnique($uuid)) {
            $uuid = Generator::genGeneralUUID($this->currentObjectId);
        }
        return $uuid;
    }

    public function getGroupUUID() {
        $guuid = '';
        while($guuid == '' || !$this->bo->isGroupIdUnique($guuid)) {
            $guuid = Generator::genGroupKey();
        }
        return $guuid;
    }

    public function getAgentUUID() {
        $auuid = '';
        while($auuid == '' || !$this->bo->isAgentIdUnique($auuid)) {
            $auuid = Generator::genAgentKey();
        }
        return $auuid;
    }

    public function getActivationUUID() {
        $auuid = '';
        while($auuid == '' || !$this->bo->isActivationIdUnique($auuid)) {
            $auuid = Generator::genEmailActivationKey();
        }
        return $auuid;
    }
}